#pragma once
#include <iostream>
#include <string>
#include "Log.hpp"
#include <error.h>
#include <string.h>
#include "nocopy.hpp"
#include "Comm.hpp"
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <signal.h>
#include"InetAddr.hpp"

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

Log lg;

const static int default_backlog = 5; // TODO
class TcpServer;

class ThreadData
{
public:
    ThreadData(int sockfd, TcpServer *svr_ptr,struct sockaddr_in& peer)
        : _sockfd(sockfd), _svr_ptr(svr_ptr),addr(peer)
    {
    }
    TcpServer *GetServer()
    {
        return _svr_ptr;
    }
    int Sockfd()
    {
        return _sockfd;
    }
    ~ThreadData()
    {
        close(_sockfd); // 关闭套接字
    }

private:
    int _sockfd;
    TcpServer *_svr_ptr;
public:
    InetAddr addr;
};

class TcpServer : public nocopy // 用于1不想让服务器被拷贝
{
public:
    TcpServer(uint16_t port)
        : _port(port), _isrunning(false)
    {
    }
    void Init()
    {
        // 1.创建套接字
        // sockfd本质就是文件描述符
        _listen_sock = socket(AF_INET, SOCK_STREAM, 0);
        if (_listen_sock < 0)
        {
            lg.LogMessage(Fatal, "create socket error,errno code:%, error string:%s\n", errno, strerror(errno));
            exit(Socket_Err);
        }
        lg.LogMessage(Debug, "create socket success,sockfd:%d\n", _listen_sock);

        // 固定写法，解决一些少量的bind失败的问题
        int optval = 1;
        setsockopt(_listen_sock, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &optval, sizeof(optval));

        // 2.绑定套接字地址信息
        struct sockaddr_in local;
        memset(&local, 0, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        local.sin_addr.s_addr = INADDR_ANY; // INADDR_ANY的值为0，表示绑定到所有可用的网络接口

        // bind
        int n = ::bind(_listen_sock, (struct sockaddr *)&local, sizeof(local)); // 将套接字地址结构体绑定到套接字
        if (n != 0)
        {
            lg.LogMessage(Fatal, "bind err ,%d:%s\n", errno, strerror(errno));
            exit(Bind_Err);
        }
        lg.LogMessage(Debug, "bind success\n");

        // 3.设置socket为监听状态，tcp特有的
        int m = listen(_listen_sock, default_backlog);
        if (m != 0)
        {
            lg.LogMessage(Fatal, "listen err ,%d:%s\n", errno, strerror(errno));
            exit(Listen_Err);
        }
        lg.LogMessage(Debug, "listen successs\n");
    }
    // TCP连接服务，是全双工通信的
    void serverice(int sockfd)
    {
        char buffer[1024];
        while (true)
        {
            size_t n = read(sockfd, buffer, sizeof(buffer) - 1);
            if (n > 0)
            {
                buffer[n] = 0;
                cout << "client say#  " << buffer << endl;

                string echo_string = "server say#";
                echo_string += buffer;
                write(sockfd, echo_string.c_str(), echo_string.size());
            }
            else if (n == 0) // read如果返回值是0，表示读到了文件的结尾（对端关闭了）
            {
                lg.LogMessage(Info, "client close the connection\n");
                break;
            }
            else
            {
                lg.LogMessage(Error, "read socket error,errno code:%d,error string:%s\n", errno, strerror(errno));
                break;
            }
        }
    }

      // TCP连接服务，是全双工通信的
    void serverice(int sockfd,InetAddr& addr)
    {
        char buffer[1024];
        while (true)
        {
            size_t n = read(sockfd, buffer, sizeof(buffer) - 1);
            if (n > 0)
            {
                buffer[n] = 0;
                //cout << "client say#  " << buffer << endl;
                cout<<addr.PrintDebug()<<"$"<<buffer<<endl;

                string echo_string = "server say#";
                echo_string += buffer;
                write(sockfd, echo_string.c_str(), echo_string.size());
            }
            else if (n == 0) // read如果返回值是0，表示读到了文件的结尾（对端关闭了）
            {
                lg.LogMessage(Info, "client close the connection\n");
                break;
            }
            else
            {
                lg.LogMessage(Error, "read socket error,errno code:%d,error string:%s\n", errno, strerror(errno));
                break;
            }
        }
    }

    static void *HandlerRequest(void *args)
    {
        ThreadData *td = static_cast<ThreadData *>(args); //
        pthread_detach(pthread_self());                   // 分离线程，让主线程和新线程分离，防止主线程退出而导致新线程无法正常退出
        td->GetServer()->serverice(td->Sockfd(),td->addr);

        delete td;
        return nullptr;
    }

    void Start()
    {
        _isrunning = true;
        signal(SIGCHLD, SIG_IGN); // 忽略子进程结束信号,让子进程自己释放自己的资源
        while (_isrunning)
        {
            // 4.获取用户连接
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            int sockfd = accept(_listen_sock, (struct sockaddr *)&peer, &len);
            if (sockfd < 0)
            {
                lg.LogMessage(Warning, "accept socket error,errno code:%d,error string:%s\n", errno, strerror(errno));
                continue;
            }
            lg.LogMessage(Debug, "accept a new client,sockfd:%d\n", sockfd);

            // 5.提供服务
            // v4多线程
            ThreadData *td = new ThreadData(sockfd, this,peer);

            pthread_t tid;
            tid = pthread_create(&tid, nullptr, HandlerRequest, td);

            // 主线程和新线程，不需要关闭文件描述符，将我们的线程分离
        }
    }

    ~TcpServer()
    {
    }

private:
    uint16_t _port;
    int _listen_sock; // 这个套接字主要用于监听
    // 不是用于和client进行通信的
    bool _isrunning;
};